package com.system.core.pay.wechat;

import jakarta.validation.Valid;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.system.core.pay.PayService;
import com.system.core.pay.util.WechatUtils;
import com.system.core.pay.wechat.dto.NativeReq;
import com.system.core.pay.wechat.dto.NativeReq.CommReqAmountInfo;
import com.system.core.pay.wechat.dto.NativeRsp;
import com.system.core.pay.wechat.dto.WechatClientReq;

@Service
@Validated
public class WechatPayNativeService implements PayService {

	private String apiV3Key="sRppcVq39pQgYebcH8qSHFkA4l7ZWTl2";
	private String privateKey="-----BEGIN PRIVATE KEY-----\r\n"
			+ "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyRbSfJZpiqtZ7\r\n"
			+ "7w3GI+17W6+37GebHTD/hzeHjEH7JJOAvGhqCxxFrxA7w0IiCfw/oAu/xj8LaIJ5\r\n"
			+ "vHiNzeXFgJbhsXR7x9a1GvT2nGYd7GuM80J8RGIMgU2AahZYJUOjwBQ2Q7kb7B0x\r\n"
			+ "hJDhDNIDUsWwAuG6H2pdq8NTrMb9e5YbZR+grU/SZsjBjjHtDTQanEl6f2J0BbQ5\r\n"
			+ "gbk6Y7uGh9gDg9VTPu5VFeyiECCSKgnTOreWr48wWy+LjJd+37zAOcxHwQybNXxt\r\n"
			+ "qsjmPHICw2Arb1YxnJ6XeNQ/EV35EGew5kzlBr0JuB2V+OwVa1CHQVzLToa46FP4\r\n"
			+ "ZZ79naMlAgMBAAECggEAVby+fJfaIz/kfaBf8H5Q9bYH0Z4JygkFCq/eXftvtDhI\r\n"
			+ "FG8IjI+hXkYuuX9T7Aj/Xx466FWQ9oyhy6iAFjsDGbSZXBw7WFipA1rem0hmuFd+\r\n"
			+ "9j/8JsXA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oGBALFYXNJbDO9JpYASuWl/\r\n"
			+ "IATOkvNq9I99XUKUSJx0t542VyQG2UyGk9vQctO6aNxFVC55NgyQbUJVYtNGf5yh\r\n"
			+ "pS/dCrT3QVZsBaWm67hk/Bt6c3t0SbdpojnSq2c26sJWmXGB0fC/74/j7BinPSUu\r\n"
			+ "eJtUFjwvzPtden4M8TRCHcP/\r\n"
			+ "-----END PRIVATE KEY-----\r\n"
			+ "";
	private String merchantId="1684748951";
	private String serialNumber="36FD5D33F9891D51E1E389B30D3574918B5445C6";

	/**
	 * 准备工作：https://pay.weixin.qq.com/docs/merchant/products/native-payment/preparation.html
	 */
	public NativeRsp prepay(@Valid NativeReq preOrderReq) throws Exception {
		var req = WechatClientReq.builder()
				.privateKey(privateKey).serialNumber(serialNumber)
				.merchantId(merchantId).apiV3Key(apiV3Key).autoUpdate(true).build();
		
		var closeableHttpClient = WechatUtils.getClient(req);
		
		HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
		String reqdata = JSONObject.toJSONString(preOrderReq,
				SerializerFeature.PrettyFormat);
		System.out.println(reqdata);
		StringEntity entity = new StringEntity(reqdata, "utf-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
		httpPost.setHeader("Accept", "application/json");
		
		CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
		try {
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) { // 处理成功
				return JSONObject.parseObject(EntityUtils.toString(response.getEntity()), NativeRsp.class);
			} else if (statusCode == 204) { // 处理成功，无返回Body
				return null;
			} else {
				var entityRsp = response.getEntity();
				var nativeRsp = JSONObject.parseObject(EntityUtils.toString(entityRsp), NativeRsp.class);
				EntityUtils.consume(entityRsp);
				return nativeRsp;
			}
		} finally {
			response.close();
		}
	}


	public static void main(String[] args) throws Exception {
		WechatPayNativeService wechatPayNativeService = new WechatPayNativeService();
		NativeReq nativeReq = new NativeReq();
		nativeReq.setAppid("wxc0dee1145e093f0c");
		nativeReq.setMchid("1684748951");
		nativeReq.setOutTradeNo("1217752501201407033233368019");
		nativeReq.setDescription("测试订单");
		nativeReq.setNotifyUrl("https://www.baidu.com");
		CommReqAmountInfo commReqAmountInfo = new CommReqAmountInfo();
		commReqAmountInfo.setTotal(1);
		nativeReq.setAmount(commReqAmountInfo);
		NativeRsp nativeRsp = wechatPayNativeService.prepay(nativeReq);
		System.out.println(nativeRsp);
	}
}